package com.easy.web.controller;

import com.easy.web.utils.HttpClientUtil;
import com.easy.web.utils.StringUtil;
import com.easy.web.utils.ViewUtils;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/4/20.
 */
@Controller
@RequestMapping("openId")
public class WeiXinOpenIdController {

    @Value("${pay.app_id}")
    private String appId;
    @Value("${pay.secret}")
    private String apiKey;
    @Value("${pay.token.url}")
    private String tokenUrl;
    @Value("${pay.userInfo.url}")
    private String userInfoUrl;
    private static final Logger logger = LoggerFactory.getLogger(WeiXinOpenIdController.class);
    private CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setConnectionTimeToLive(1, TimeUnit.MINUTES)
            .setMaxConnTotal(100).build();

    @RequestMapping(value = "getOpenId")
    public ModelAndView getOpenId(HttpServletRequest request){
        //获取微信回调code
        String code=request.getParameter("code");
        HttpClientUtil.createHttpClient(httpClient);
        Map<String,Object> params=new HashedMap();
        params.put("appid",appId);
        params.put("secret",apiKey);
        params.put("code",code);
        params.put("grant_type","authorization_code");
        String result="";
//        logger.info("参数"+params);
        try {
            result=HttpClientUtil.httpGetRequest(tokenUrl,params);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        logger.info("微信auth2返回："+result);
//        JSONObject obj=JSONObject.fromObject(result);
//        String openId=obj.optString("openid");
//        String userInfo="";
//        if(StringUtil.isNotEmpty(openId)){
//            Map<String,Object> params1=new HashedMap();
//            params1.put("access_token",obj.optString("access_token"));
//            params1.put("openid",obj.optString("openid"));
//            params1.put("lang","zh_CN");
//
//            try {
//                userInfo=HttpClientUtil.httpGetRequest(userInfoUrl,params1);
//            } catch (URISyntaxException e) {
//                e.printStackTrace();
//            }
//            logger.info("微信openid信息："+userInfo);
//        }
        return new ModelAndView("", ViewUtils.mapSuccess(result));
    }
}
